/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2021/1/31 21:45:10
 *        Description: 暂无
 ***********************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.Caching.AutoMate.RedisCache;
using CoreCms.Net.Configuration;
using CoreCms.Net.DTO;
using CoreCms.Net.Filter;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.Api;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.Excel;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Services;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Web.Admin.Infrastructure;
using CoreCms.Net.WeChat.Service.HttpClients;
using DotLiquid.Util;
using Flurl.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using SqlSugar;
using static CoreCms.Net.Web.Admin.Controllers.CoreCmsUserController;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 订单表
    ///</summary>
    [Description("订单表")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class CoreCmsOrderController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ICoreCmsOrderServices _coreCmsOrderServices;
        private readonly ICoreCmsUserServices _userServices;
        private readonly ICoreCmsAreaServices _areaServices;
        private readonly ICoreCmsBillAftersalesServices _aftersalesServices;
        private readonly ICoreCmsBillPaymentsServices _billPaymentsServices;
        private readonly ICoreCmsBillDeliveryServices _billDeliveryServices;
        private readonly ICoreCmsStoreServices _storeServices;
        private readonly ICoreCmsLogisticsServices _logisticsServices;
        private readonly ICoreCmsPaymentsServices _paymentsServices;
        private readonly ICoreCmsSettingServices _settingServices;
        private readonly ICoreCmsUserWeChatInfoServices _userWeChatInfoServices;
        private readonly IRedisOperationRepository _redisOperationRepository;
        private readonly CoreCms.Net.WeChat.Service.HttpClients.IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;
        private readonly IWeChatShippingDeliveryServices _weChatShippingDeliveryServices;

        private readonly ICoreCmsDistributionOrderServices _distributionOrderServices;
        private readonly ICoreCmsAgentOrderServices _agentOrderServices;


        private readonly ICoreCmsOrderItemServices _orderItemServices;
        private readonly ICoreCmsSourceServices _coreCmsSourceServices;
        private readonly ICoreCmsCustomerClassServices _coreCmsCustomerClassServices;
        private readonly ICoreCmsOrderTypeServices _coreCmsOrderTypeServices;
        private readonly ICoreCmsWechatnumberServices _coreCmsWechatnumberServices;
        private readonly ICoreCmsCustomerGroupServices _coreCmsCustomerGroupServices;
        private readonly ISysUserServices _sysUserServices;
        private readonly ICoreCmsNewCartServices _coreCmsNewCartServices;
        private readonly ICoreCmsDepartmentServices _coreCmsDepartmentServices;
        private readonly ICoreCmsCompanyServices _coreCmsCompanyServices;
        private readonly ICoreCmsGroupServices _coreCmsGroupServices;
        private readonly ICoreCmsOrderLogServices _coreCmsOrderLogServices;
        private readonly IHttpContextUser _user;
        private readonly ICoreCmsProductsServices _coreCmsProductsServices;
        private readonly ICoreCmsGoodsServices _coreCmsGoodsServices;
        private readonly ICoreCmsStockLogServices _coreCmsStockLogServices;
        private readonly ICoreCmsStockServices _coreCmsStockServices;
        private readonly ICoreCmsUserServices _coreCmsUserServices;
        /// <summary>
        /// 构造函数
        ///</summary>
        public CoreCmsOrderController(IWebHostEnvironment webHostEnvironment
            , ICoreCmsOrderServices coreCmsOrderServices
            , ICoreCmsUserServices userServices
            , ICoreCmsAreaServices areaServices
            , ICoreCmsBillAftersalesServices aftersalesServices
            , ICoreCmsStoreServices storeServices
            , ICoreCmsLogisticsServices logisticsServices
            , ICoreCmsBillPaymentsServices billPaymentsServices
            , ICoreCmsPaymentsServices paymentsServices
            , ICoreCmsSettingServices settingServices, ICoreCmsUserWeChatInfoServices userWeChatInfoServices, IRedisOperationRepository redisOperationRepository, ICoreCmsBillDeliveryServices billDeliveryServices, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, ICoreCmsOrderItemServices orderItemServices, IWeChatShippingDeliveryServices weChatShippingDeliveryServices, ICoreCmsDistributionOrderServices distributionOrderServices, ICoreCmsAgentOrderServices agentOrderServices
              ,ICoreCmsCustomerClassServices coreCmsCustomerClassServices
            , ICoreCmsSourceServices coreCmsSourceServices
            , ICoreCmsOrderTypeServices coreCmsOrderTypeServices
            , ICoreCmsWechatnumberServices coreCmsWechatnumberServices
            , ICoreCmsCustomerGroupServices coreCmsCustomerGroupServices
            ,ISysUserServices sysUserServices
            ,ICoreCmsNewCartServices coreCmsnewCartServices
            ,ICoreCmsDepartmentServices coreCmsDepartmentServices
            ,ICoreCmsCompanyServices coreCmsCompanyServices
            ,ICoreCmsGroupServices coreCmsGroupServices
            ,ICoreCmsOrderLogServices coreCmsOrderLogServices
            ,IHttpContextUser user
            ,ICoreCmsProductsServices productsServices
            ,ICoreCmsGoodsServices goodsServices
            , ICoreCmsStockLogServices coreCmsStockLogServices
            ,ICoreCmsStockServices coreCmsStockServices
            ,ICoreCmsUserServices coreCmsUserServices
            
            )
        {
            _webHostEnvironment = webHostEnvironment;
            _coreCmsOrderServices = coreCmsOrderServices;
            _userServices = userServices;
            _areaServices = areaServices;
            _aftersalesServices = aftersalesServices;
            _storeServices = storeServices;
            _logisticsServices = logisticsServices;
            _billPaymentsServices = billPaymentsServices;
            _paymentsServices = paymentsServices;
            _settingServices = settingServices;
            _userWeChatInfoServices = userWeChatInfoServices;
            _redisOperationRepository = redisOperationRepository;
            _billDeliveryServices = billDeliveryServices;
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
            _orderItemServices = orderItemServices;
            _weChatShippingDeliveryServices = weChatShippingDeliveryServices;
            _distributionOrderServices = distributionOrderServices;
            _agentOrderServices = agentOrderServices;
            _coreCmsCustomerClassServices = coreCmsCustomerClassServices;
            _coreCmsSourceServices = coreCmsSourceServices;
            _coreCmsOrderTypeServices = coreCmsOrderTypeServices;
            _coreCmsWechatnumberServices = coreCmsWechatnumberServices;
            _coreCmsCustomerGroupServices = coreCmsCustomerGroupServices;
            _sysUserServices = sysUserServices;
            _coreCmsNewCartServices = coreCmsnewCartServices;
            _coreCmsDepartmentServices = coreCmsDepartmentServices;
            _coreCmsCompanyServices= coreCmsCompanyServices;
            _coreCmsGroupServices = coreCmsGroupServices;
            _coreCmsOrderLogServices= coreCmsOrderLogServices;
            _user= user;
            _coreCmsProductsServices = productsServices;
            _coreCmsGoodsServices = goodsServices;
            _coreCmsStockLogServices = coreCmsStockLogServices;
            _coreCmsStockServices = coreCmsStockServices;
            _coreCmsUserServices= coreCmsUserServices;
        }

        #region 获取列表============================================================
        // POST: Api/CoreCmsOrder/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            //AdminUiCallBack
            var jm = new AdminUiCallBack();
            var roleName = _user.roleName;//角色

            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsOrder>();
            //获取排序字段
    
            //订单号 nvarchar
            var orderId = Request.Form["orderId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(orderId))
            {
                where = where.And(p => p.orderId.Contains(orderId));
            }
            if (roleName == "总经理"||roleName=="跟单"||roleName=="审单")
            {
                where = where.And(p => p.companyId == _user.companyId);
            }
            if (roleName == "经理"||roleName=="销售经理")
            {
                var departmentId1 = _user.departmentId;
                where = where.And(p => p.departmentId == departmentId1);
            }
            if (roleName == "组长"||roleName=="销售主管")
            {
                var _groupId = _user.groupId;
                where = where.And(p => p.groupId == _groupId);
            }
            if (roleName == "组员")
            {

                where = where.And(p => p.sysid == Convert.ToInt32(_user.userId));
            }
            //订单状态 int
            var status = Request.Form["status"].FirstOrDefault().ObjectToInt(0);
            if (status > 0)
            {
                where = where.And(p => p.status == status);
            }
            //订单类型 int
            var orderType = Request.Form["orderType"].FirstOrDefault();
            if (!string.IsNullOrEmpty(orderType))
            {
                where = where.And(p => p.orderTypeName.Contains(orderType));
            }
            //发货状态 int
            var shipStatus = Request.Form["shipStatus"].FirstOrDefault().ObjectToInt(0);
            if (shipStatus > 0)
            {
                where = where.And(p => p.shipStatus == shipStatus);
            }
            //支付状态 int
            var payStatus = Request.Form["payStatus"].FirstOrDefault().ObjectToInt(0);
            if (payStatus > 0)
            {
                where = where.And(p => p.payStatus == payStatus);
            }
            //支付方式代码 nvarchar
            var paymentCode = Request.Form["paymentCode"].FirstOrDefault();
            if (!string.IsNullOrEmpty(paymentCode))
            {
                where = where.And(p => p.paymentCode.Contains(paymentCode));
            }
            //售后状态 int
            var confirmStatus = Request.Form["confirmStatus"].FirstOrDefault().ObjectToInt(0);
            if (confirmStatus > 0)
            {
                where = where.And(p => p.confirmStatus == confirmStatus);
            }
            //订单来源 int
            var source = Request.Form["sourceId"].FirstOrDefault().ObjectToInt(0);
            if (source > 0)
            {
                where = where.And(p => p.sourceId == source);
            }
            //收货方式 int
            var receiptType = Request.Form["receiptType"].FirstOrDefault().ObjectToInt(0);
            if (receiptType > 0)
            {
                where = where.And(p => p.receiptType == receiptType);
            }

            //收货人姓名 nvarchar
            var shipName = Request.Form["shipName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipName))
            {
                where = where.And(p => p.shipName.Contains(shipName));
            }
            //收货人地址 nvarchar
            var shipAddress = Request.Form["shipAddress"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipAddress))
            {
                where = where.And(p => p.shipAddress.Contains(shipAddress));
            }

            //收货电话 nvarchar
            var shipMobile = Request.Form["shipMobile"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipMobile))
            {
                where = where.And(p => p.shipMobile.Contains(shipMobile));
            }
            //收货电话 nvarchar
            var number = Request.Form["number"].FirstOrDefault();
            if (!string.IsNullOrEmpty(number))
            {
                where = where.And(p => p.number.Contains(number));
            }

            //付款单号 nvarchar
            var paymentId = Request.Form["paymentId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(paymentId))
            {
                where = where.And(p => p.shipMobile.Contains(paymentId));
            }

            // datetime
            var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            //商品名称 nvarchar
            var goodName = Request.Form["goodName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(goodName))
            {
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.name.Contains(goodName), p => p.createTime, OrderByType.Desc, true);
                if (orderItems.Any())
                {
                    var itemIds = orderItems.Select(p => p.orderId).ToList();
                    where = where.And(p => itemIds.Contains(p.orderId));
                }
            }

            //商品编码 nvarchar
            var goodSn = Request.Form["goodSn"].FirstOrDefault();
            if (!string.IsNullOrEmpty(goodSn))
            {
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.sn.Contains(goodSn), p => p.createTime, OrderByType.Desc, true);
                if (orderItems.Any())
                {
                    var itemIds = orderItems.Select(p => p.orderId).ToList();
                    where = where.And(p => itemIds.Contains(p.orderId));
                }
            }

            //订单状态 int
            var orderUnifiedStatus = Request.Form["orderUnifiedStatus"].FirstOrDefault().ObjectToInt(0);
            if (orderUnifiedStatus > 0)
            {
                if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Normal)
                {
                    //下单
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Normal));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Confirm)
                {
                    //待确认
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Confirm));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Approve)
                {
                    //待批准
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Approve));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Shipment)
                {
                    //待发货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Shipment));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Send)
                {
                    //已发货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Send));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Signed)
                {
                    //已签收
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Signed));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Complete)
                {
                    //已完成
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Complete));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.CancelOrder)
                {
                    //已退货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.CancelOrder));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.delete)
                {
                    //已取消
                    where = where.And(p => p.isdel == true);
                }
            }
            else
            {
                where = where.And(p => p.isdel == false);
            }

            //获取数据
            var list = await _coreCmsOrderServices.QueryPageAsync(where, p => p.createTime, OrderByType.Desc, pageCurrent, pageSize, true);
            if (list != null && list.Any())
            {
                var areaCache = await _areaServices.GetCaChe();
                foreach (var item in list)
                {
                    item.operating = _coreCmsOrderServices.GetOperating(item.orderId, item.status, item.payStatus, item.shipStatus, item.receiptType, item.isdel);
                    item.afterSaleStatus = "";
                    if (item.aftersalesItem != null && item.aftersalesItem.Any())
                    {
                        foreach (var sale in item.aftersalesItem)
                        {
                            item.afterSaleStatus += EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillAftersalesStatus>(sale.status) + "<br>";
                        }
                    }
                    var areas = await _areaServices.GetAreaFullName(item.shipAreaId, areaCache);
                    item.shipAreaName = areas.status ? areas.data + "-" + item.shipAddress : item.shipAddress;
                }
            }

            //返回数据
            jm.data = list;

           
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.otherData = new
            {
                list.HasNextPage,
                list.HasPreviousPage,
                list.PageIndex,
                list.PageSize,
                list.TotalCount,
                list.TotalPages
            };
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion
        #region 待发货列表============================================================
        // POST: Api/CoreCmsOrder/GetPageList
        /// <summary>
        /// 待发货列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("待发货列表")]
        public async Task<AdminUiCallBack> GetPageListDeliver()
        {
            //AdminUiCallBack
            var jm = new AdminUiCallBack();
            var roleName = _user.roleName;//角色

            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsOrder>();
            //获取排序字段
           // where = where.And(p => p.status==5);
            //订单号 nvarchar
            var orderId = Request.Form["orderId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(orderId))
            {
                where = where.And(p => p.orderId.Contains(orderId));
            }

            //订单状态 int
            var status = Request.Form["status"].FirstOrDefault().ObjectToInt(0);
            if (status > 0)
            {
                where = where.And(p => p.status == status);
            }
            //订单类型 int
            var orderType = Request.Form["orderType"].FirstOrDefault();
            if (!string.IsNullOrEmpty(orderType))
            {
                where = where.And(p => p.orderTypeName.Contains(orderType));
            }
            if (roleName == "总经理")
            {
                //var departmentId1 = _user.departmentId;
                where = where.And(p => p.companyId == _user.companyId);
            }
            //发货状态 int
            var shipStatus = Request.Form["shipStatus"].FirstOrDefault().ObjectToInt(0);
            if (shipStatus > 0)
            {
                where = where.And(p => p.shipStatus == shipStatus);
            }
            //支付状态 int
            var payStatus = Request.Form["payStatus"].FirstOrDefault().ObjectToInt(0);
            if (payStatus > 0)
            {
                where = where.And(p => p.payStatus == payStatus);
            }
            //支付方式代码 nvarchar
            var paymentCode = Request.Form["paymentCode"].FirstOrDefault();
            if (!string.IsNullOrEmpty(paymentCode))
            {
                where = where.And(p => p.paymentCode.Contains(paymentCode));
            }
            //售后状态 int
            var confirmStatus = Request.Form["confirmStatus"].FirstOrDefault().ObjectToInt(0);
            if (confirmStatus > 0)
            {
                where = where.And(p => p.confirmStatus == confirmStatus);
            }
            //订单来源 int
            var source = Request.Form["sourceId"].FirstOrDefault().ObjectToInt(0);
            if (source > 0)
            {
                where = where.And(p => p.sourceId == source);
            }
            //收货方式 int
            var receiptType = Request.Form["receiptType"].FirstOrDefault().ObjectToInt(0);
            if (receiptType > 0)
            {
                where = where.And(p => p.receiptType == receiptType);
            }
            //客户编号 nvarchar
            var number = Request.Form["number"].FirstOrDefault();
            if (!string.IsNullOrEmpty(number))
            {
                where = where.And(p => p.number.Contains(number));
            }
            //收货人姓名 nvarchar
            var shipName = Request.Form["shipName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipName))
            {
                where = where.And(p => p.shipName.Contains(shipName));
            }
            //收货人地址 nvarchar
            var shipAddress = Request.Form["shipAddress"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipAddress))
            {
                where = where.And(p => p.shipAddress.Contains(shipAddress));
            }

            //收货电话 nvarchar
            var shipMobile = Request.Form["shipMobile"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipMobile))
            {
                where = where.And(p => p.shipMobile.Contains(shipMobile));
            }

            //付款单号 nvarchar
            var paymentId = Request.Form["paymentId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(paymentId))
            {
                where = where.And(p => p.shipMobile.Contains(paymentId));
            }

            // datetime
            var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            if (roleName == "经理")
            {
                var departmentId1 = _user.departmentId;
                where = where.And(p => p.departmentId == departmentId1);
            }
            if (roleName == "组长")
            {
                var _groupId = _user.groupId;
                where = where.And(p => p.groupId == _groupId);
            }
            if (roleName == "组员")
            {
                var groupId1 = _user.groupId;
                where = where.And(p => p.groupId == groupId1);
            }
            //商品名称 nvarchar
            var goodName = Request.Form["goodName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(goodName))
            {
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.name.Contains(goodName), p => p.createTime, OrderByType.Desc, true);
                if (orderItems.Any())
                {
                    var itemIds = orderItems.Select(p => p.orderId).ToList();
                    where = where.And(p => itemIds.Contains(p.orderId));
                }
            }

            //商品编码 nvarchar
            var goodSn = Request.Form["goodSn"].FirstOrDefault();
            if (!string.IsNullOrEmpty(goodSn))
            {
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.sn.Contains(goodSn), p => p.createTime, OrderByType.Desc, true);
                if (orderItems.Any())
                {
                    var itemIds = orderItems.Select(p => p.orderId).ToList();
                    where = where.And(p => itemIds.Contains(p.orderId));
                }
            }

            //订单状态 int
            var orderUnifiedStatus = Request.Form["orderUnifiedStatus"].FirstOrDefault().ObjectToInt(0);
            if (orderUnifiedStatus > 0)
            {
                if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Normal)
                {
                    //下单
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Normal));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Confirm)
                {
                    //待确认
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Confirm));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Approve)
                {
                    //待批准
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Approve));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Shipment)
                {
                    //待发货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Shipment));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Send)
                {
                    //已发货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Send));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Signed)
                {
                    //已签收
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Signed));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.Complete)
                {
                    //已完成
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Complete));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderStatus.CancelOrder)
                {
                    //已退货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.CancelOrder));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.delete)
                {
                    //已取消
                    where = where.And(p => p.isdel == true);
                }
            }
            else
            {
                where = where.And(p => p.isdel == false&&p.status==5);
            }

            //获取数据
            var list = await _coreCmsOrderServices.QueryPageAsync(where, p => p.createTime, OrderByType.Desc, pageCurrent, pageSize, true);
            if (list != null && list.Any())
            {
                var areaCache = await _areaServices.GetCaChe();
                foreach (var item in list)
                {
                    item.operating = _coreCmsOrderServices.GetOperating(item.orderId, item.status, item.payStatus, item.shipStatus, item.receiptType, item.isdel);
                    item.afterSaleStatus = "";
                    if (item.aftersalesItem != null && item.aftersalesItem.Any())
                    {
                        foreach (var sale in item.aftersalesItem)
                        {
                            item.afterSaleStatus += EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillAftersalesStatus>(sale.status) + "<br>";
                        }
                    }
                    var areas = await _areaServices.GetAreaFullName(item.shipAreaId, areaCache);
                    item.shipAreaName = areas.status ? areas.data + "-" + item.shipAddress : item.shipAddress;
                }
            }

            //返回数据
            jm.data = list;


            jm.code = 0;
            jm.count = list.TotalCount;
            jm.otherData = new
            {
                list.HasNextPage,
                list.HasPreviousPage,
                list.PageIndex,
                list.PageSize,
                list.TotalCount,
                list.TotalPages
            };
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion
        #region 首页数据============================================================
        // POST: Api/CoreCmsOrder/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public async Task<AdminUiCallBack> GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            StringBuilder where = new StringBuilder();
            int all = 0;//所有
            var normalCount = 0;//下单
            var confirmCount = 0;//确认
            var approveCount = 0;//批准
            var shipmentCount = 0;//待发货
            var sendCount = 0;//已发货
            var signedCount = 0; //已签收
            var completeCount = 0;//已完成
            var cancelCount = 0;//退货
            var warehouseCount = 0;//待入库
            //全部
            //var all = await _coreCmsOrderServices.GetCountAsync(p => p.isdel == false);
            // all = _coreCmsOrderServices.GetCount(" ", "");
            //if (_user.roleName == "总经理")
            //{
            //   /// where.Append(" and c.companyId=" + _user.companyId + "");
            //    all =  _coreCmsOrderServices.GetCount(" and c.companyId="+_user.companyId+"", "");
            //    normalCount = _coreCmsOrderServices.GetCount(" and a.status=1 and c.companyId="+ _user.companyId + "", "");
            //    confirmCount = _coreCmsOrderServices.GetCount(" and a.status=4 and c.companyId="+ _user.companyId + "", "");
            //    approveCount = _coreCmsOrderServices.GetCount(" and a.status=5  and c.companyId="+_user.companyId+"", "");
            //    shipmentCount = _coreCmsOrderServices.GetCount(" and a.status=7 and c.companyId="+ _user.companyId + "", "");
            //    sendCount = _coreCmsOrderServices.GetCount(" and a.status=6 and c.companyId="+ _user.companyId + "", "");
            //    signedCount = _coreCmsOrderServices.GetCount(" and a.status=8 and c.companyId="+ _user.companyId + "", "");
            //    completeCount = _coreCmsOrderServices.GetCount(" and a.status=2 and c.companyId="+ _user.companyId + "", "");
            //    cancelCount = _coreCmsOrderServices.GetCount(" and a.status=9 and c.companyId="+ _user.companyId + "", "");
            //    warehouseCount = _coreCmsOrderServices.GetCount(" and a.status=9 and c.companyId="+ _user.companyId + "", "");
            //}
            //if (_user.roleName == "经理")
            //{
            //    /// where.Append(" and c.companyId=" + _user.companyId + "");
            //    all = _coreCmsOrderServices.GetCount(" and c.departmentId=" + _user.departmentId + "", "");
            //    normalCount = _coreCmsOrderServices.GetCount(" and a.status=1 and c.departmentId=" + _user.departmentId + "", "");
            //    confirmCount = _coreCmsOrderServices.GetCount(" and a.status=4 and c.departmentId=" + _user.departmentId + "", "");
            //    approveCount = _coreCmsOrderServices.GetCount(" and a.status=5  and c.departmentId=" + _user.departmentId + "", "");
            //    shipmentCount = _coreCmsOrderServices.GetCount(" and a.status=7 and c.departmentId=" + _user.departmentId + "", "");
            //    sendCount = _coreCmsOrderServices.GetCount(" and a.status=6 and c.departmentId=" + _user.departmentId + "", "");
            //    signedCount = _coreCmsOrderServices.GetCount(" and a.status=8 and c.departmentId=" + _user.departmentId + "", "");
            //    completeCount = _coreCmsOrderServices.GetCount(" and a.status=2 and c.departmentId=" + _user.departmentId + "", "");
            //    cancelCount = _coreCmsOrderServices.GetCount(" and a.status=9 and c.departmentId=" + _user.departmentId + "", "");
            //    warehouseCount = _coreCmsOrderServices.GetCount(" and a.status=9 and c.departmentId=" + _user.departmentId + "", "");
            //}
            //if (_user.roleName == "组长")
            //{
            //    /// where.Append(" and c.companyId=" + _user.companyId + "");
            //    all = _coreCmsOrderServices.GetCount(" and c.groupId=" + _user.companyId + "", "");
            //    normalCount = _coreCmsOrderServices.GetCount(" and a.status=1 and c.groupId=" + _user.departmentId + "", "");
            //    confirmCount = _coreCmsOrderServices.GetCount(" and a.status=4 and c.groupId=" + _user.departmentId + "", "");
            //    approveCount = _coreCmsOrderServices.GetCount(" and a.status=5  and c.groupId=" + _user.departmentId + "", "");
            //    shipmentCount = _coreCmsOrderServices.GetCount(" and a.status=7 and c.groupId=" + _user.departmentId + "", "");
            //    sendCount = _coreCmsOrderServices.GetCount(" and a.status=6 and c.groupId=" + _user.departmentId + "", "");
            //    signedCount = _coreCmsOrderServices.GetCount(" and a.status=8 and c.groupId=" + _user.departmentId + "", "");
            //    completeCount = _coreCmsOrderServices.GetCount(" and a.status=2 and c.groupId=" + _user.departmentId + "", "");
            //    cancelCount = _coreCmsOrderServices.GetCount(" and a.status=9 and c.groupId=" + _user.departmentId + "", "");
            //    warehouseCount = _coreCmsOrderServices.GetCount(" and a.status=9 and c.groupId=" + _user.departmentId + "", "");
            //}
            //if (_user.roleName == "组员")
            //{
            //    /// where.Append(" and c.companyId=" + _user.companyId + "");
            //    all = _coreCmsOrderServices.GetCount(" and a.sysid=" + _user.userId + "", "");
            //    normalCount = _coreCmsOrderServices.GetCount(" and a.status=1 and a.sysid=" + _user.userId + "", "");
            //    confirmCount = _coreCmsOrderServices.GetCount(" and a.status=4 and a.sysid=" + _user.userId + "", "");
            //    approveCount = _coreCmsOrderServices.GetCount(" and a.status=5  and a.sysid=" + _user.userId + "", "");
            //    shipmentCount = _coreCmsOrderServices.GetCount(" and a.status=7 and a.sysid=" + _user.userId + "", "");
            //    sendCount = _coreCmsOrderServices.GetCount(" and a.status=6 and a.sysid=" + _user.userId + "", "");
            //    signedCount = _coreCmsOrderServices.GetCount(" and a.status=8 and a.sysid=" + _user.userId + "", "");
            //    completeCount = _coreCmsOrderServices.GetCount(" and a.status=2 and a.sysid=" + _user.userId + "", "");
            //    cancelCount = _coreCmsOrderServices.GetCount(" and a.status=9 and a.sysid=" + _user.userId + "", "");
            //    warehouseCount = _coreCmsOrderServices.GetCount(" and a.status=9 and a.sysid=" + _user.userId + "", "");
            //}
            ////下单
            //  var normalWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Normal);
          //   var normalCount = await _coreCmsOrderServices.GetCountAsync(normalWhere);
            //待确认
            // var confirmWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Confirm);
            // var confirmCount = await _coreCmsOrderServices.GetCountAsync(confirmWhere);
            //待批准
            //  var approveWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Approve);
            //var approveCount = await _coreCmsOrderServices.GetCountAsync(approveWhere);
            //待发货
            //  var shipmentWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Shipment);
            // var shipmentCount = await _coreCmsOrderServices.GetCountAsync(shipmentWhere);
            //已发货
            //   var sendWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Send);
            // var sendCount = await _coreCmsOrderServices.GetCountAsync(sendWhere);
            //已签收
            // var signedWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Signed);
            //var signedCount = await _coreCmsOrderServices.GetCountAsync(signedWhere);
            //已完成
            // var completeWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Complete);
            // var completeCount = await _coreCmsOrderServices.GetCountAsync(completeWhere);
            //退货
            // var cancelWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.CancelOrder);
            //   var cancelCount = await _coreCmsOrderServices.GetCountAsync(cancelWhere);
            //待入库
            //   var warehouseWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Warehouse);
            //var warehouseCount = await _coreCmsOrderServices.GetCountAsync(cancelWhere);
            //删除
            var delete = await _coreCmsOrderServices.GetCountAsync(p => p.isdel == true);


            //订单状态说明
            var orderStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderStatus>();
            //付款状态
            var payStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderPayStatus>();
            //发货状态
            var shipStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderShipStatus>();
            //订单来源
            var source = await _coreCmsSourceServices.QueryAsync(); //EnumHelper.EnumToList<GlobalEnumVars.Source>();
            //订单类型
            var orderType = EnumHelper.EnumToList<GlobalEnumVars.OrderTypeCrm>();
            //订单支付方式
            var paymentCode = EnumHelper.EnumToList<GlobalEnumVars.NewPaymentsTypes>();
            //收货状态
            var confirmStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderConfirmStatus>();
            //订单收货方式
            var receiptType = EnumHelper.EnumToList<GlobalEnumVars.OrderReceiptType>();
            //var companyList = await _coreCmsCompanyServices.QueryAsync();
            //var departmentList = await _coreCmsDepartmentServices.QueryAsync();
            //var groupList = await _coreCmsGroupServices.QueryAsync();
            var companyList1 = await _coreCmsCompanyServices.QueryAsync();
            var departmentList1 = await _coreCmsDepartmentServices.QueryAsync();
            var groupList1 = await _coreCmsGroupServices.QueryAsync();
            List<CoreCmsCompany> companyList = new List<CoreCmsCompany>();
            List<CoreCmsDepartment> departmentList = new List<CoreCmsDepartment>();
            List<CoreCmsGroup> groupList = new List<CoreCmsGroup>();
            var orderTypeList = await _coreCmsOrderTypeServices.QueryAsync();

            //CoreCmsCompany companyList = new CoreCmsCompany();
            if(_user.roleName == "销售经理")
            {
                departmentList = await _coreCmsDepartmentServices.QueryListByClauseAsync(p => p.companyid == _user.companyId);

            }
            if (_user.roleName == "销售主管")
            {
                groupList = await _coreCmsGroupServices.QueryListByClauseAsync(p => p.dId == _user.departmentId);

            }
            if (_user.roleName == "总经理")
            {
                companyList = await _coreCmsCompanyServices.QueryListByClauseAsync(p => p.id == _user.companyId);
            }
            if (_user.roleName.Contains("管理") || _user.roleName == "跟单" || _user.roleName == "审单" || _user.roleName == "仓库")
            {
                companyList = await _coreCmsCompanyServices.QueryAsync();
                //departmentList = await _coreCmsDepartmentServices.QueryAsync();
                //groupList = await _coreCmsGroupServices.QueryAsync();
            }
            if (_user.roleName == "组长" || _user.roleName == "组员")
            {
                //companyList = null;
                //departmentList = null;
                //groupList = null;
            }
            jm.data = new
            {
                all,
                //payment,
                //delivered,
                //receive,
                //evaluated,
                //noevaluat,
                //complete,
                //cancel,
                warehouseCount,
                cancelCount,
                completeCount,
                signedCount,
                sendCount,
                shipmentCount,
                approveCount,
                normalCount,
                confirmCount,
                delete,
                orderStatus,
                payStatus,
                shipStatus,
                orderType,
                source,
                paymentCode,
                confirmStatus,
                receiptType,
                companyList,
                departmentList,
                groupList,
                companyList1,
                departmentList1,
                groupList1
            };

            return jm;
        }
        #endregion

        #region 待发货首页数据============================================================
        // POST: Api/CoreCmsOrder/GetIndex
        /// <summary>
        /// 待发货首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("待发货首页数据")]
        public async Task<AdminUiCallBack> GetIndexDeliver()
        {
           
          //  KuaiDi100ApiPostResult aa = new KuaiDi100ApiPostResult();
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            //全部
            //var all = await _coreCmsOrderServices.GetCountAsync(p => p.isdel == false&&p.status==5);

            ////下单
            //var normalWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Normal);
            //var normalCount = await _coreCmsOrderServices.GetCountAsync(normalWhere);
            ////待确认
            //var confirmWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Confirm);
            //var confirmCount = await _coreCmsOrderServices.GetCountAsync(confirmWhere);
            //待批准
            var approveWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Approve);
            var approveCount = await _coreCmsOrderServices.GetCountAsync(approveWhere);
            ////待发货
            //var shipmentWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Shipment);
            //var shipmentCount = await _coreCmsOrderServices.GetCountAsync(shipmentWhere);
            ////已发货
            var sendWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Send);
            var sendCount = await _coreCmsOrderServices.GetCountAsync(sendWhere);
            ////已签收
            //var signedWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Signed);
            //var signedCount = await _coreCmsOrderServices.GetCountAsync(signedWhere);
            ////已完成
            //var completeWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Complete);
            //var completeCount = await _coreCmsOrderServices.GetCountAsync(completeWhere);
            //退货
            var cancelWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.CancelOrder);
            var cancelCount = await _coreCmsOrderServices.GetCountAsync(cancelWhere);
            //待入库
            var warehouseWhere = _coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderStatus.Warehouse);
            var warehouseCount = await _coreCmsOrderServices.GetCountAsync(cancelWhere);
            //删除
            var delete = await _coreCmsOrderServices.GetCountAsync(p => p.isdel == true);


            //订单状态说明
            var orderStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderStatus>();
            //付款状态
            var payStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderPayStatus>();
            //发货状态
            var shipStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderShipStatus>();
            //订单来源
            var source = EnumHelper.EnumToList<GlobalEnumVars.Source>();
            //订单类型
            var orderType = EnumHelper.EnumToList<GlobalEnumVars.OrderTypeCrm>();
            //订单支付方式
            var paymentCode = EnumHelper.EnumToList<GlobalEnumVars.PaymentsTypes>();
            //收货状态
            var confirmStatus = EnumHelper.EnumToList<GlobalEnumVars.OrderConfirmStatus>();
            //订单收货方式
            var receiptType = EnumHelper.EnumToList<GlobalEnumVars.OrderReceiptType>();
            var companyList = await _coreCmsCompanyServices.QueryAsync();
            var departmentList = await _coreCmsDepartmentServices.QueryAsync();
            var groupList = await _coreCmsGroupServices.QueryAsync();
            jm.data = new
            {
               // all,
                //payment,
                //delivered,
                //receive,
                //evaluated,
                //noevaluat,
                //complete,
                //cancel,
                warehouseCount,
                cancelCount,
                //completeCount,
                //signedCount,
                sendCount,
                //shipmentCount,
                approveCount,
                //normalCount,
                //confirmCount,
                delete,
                orderStatus,
                payStatus,
                shipStatus,
                orderType,
                source,
                paymentCode,
                confirmStatus,
                receiptType,
                companyList,
                departmentList,
                groupList
            };

            return jm;
        }
        #endregion

        /// <summary>
        /// 导入快递信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("导入快递信息")]
        public async Task<AdminUiCallBack> DoUploadUserInfos([FromBody] FMInputUserInfo entity)
        {
            var jm = new AdminUiCallBack();

            var users = new List<CoreCmsOrder>();

            var dirPath = _webHostEnvironment.WebRootPath + entity.url;
            NPOIMemoryStream stream = new NPOIMemoryStream();
            using (FileStream file = new FileStream(dirPath, FileMode.Open, FileAccess.ReadWrite))
            {
                file.CopyTo(stream);
                stream.Position = 0;

                IWorkbook workbook = null;
                if (dirPath.ToLower().Contains(".xlsx"))
                {
                    workbook = new XSSFWorkbook(stream);
                }
                else
                {
                    workbook = new HSSFWorkbook(stream);
                }

                ISheet sheet = workbook.GetSheetAt(0);

                // 从第二行开始读取数据，第一行为表头
                for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
                {
                    IRow row = sheet.GetRow(rowIndex);
                    if (row != null)
                    {
                        string orderId = row.GetCell(0)?.ToString() ?? "";
                        string expressName1 = row.GetCell(1)?.ToString() ?? "";
                        string expressNumber1 = row.GetCell(2)?.ToString() ?? "";
                        if (!string.IsNullOrEmpty(orderId))
                        {
                            var model = await _coreCmsOrderServices.QueryByClauseAsync(p => p.orderId == orderId);
                            if (model.status==5)
                            {
                                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { expressName =expressName1,expressNumber=expressNumber1,status=6,sendTime=DateTime.Now }, p => p.orderId == model.orderId);
                                if (bl==true)
                                {
                                    var stockLogs = new List<CoreCmsStockLog>();
                                    var stock = new List<CoreCmsStock>();
                                    jm.code = 0;
                                    var productList = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == orderId);
                                    if (productList.Count > 0)
                                    {
                                        
                                        foreach (var item in productList)
                                        {
                                        //  _coreCmsGoodsServices.uo(CoreCmsProducts)
                                            int count= await _coreCmsGoodsServices.NewChangeStock(item.productId,"send",item.nums);
                                            var sLog = new CoreCmsStockLog
                                            {
                                                stockId =item.orderId,
                                                productId = item.productId,
                                                goodsId = item.goodsId,
                                                nums = -item.nums,
                                                sn = item.sn,
                                                bn =string.Empty,
                                                goodsName = item.name,
                                                spesDesc = item.addon,
                                                fcreateTime=DateTime.Now
                                               
                                            };
                                            stockLogs.Add(sLog);
                                        }

                                    }
                                    var orderLog = new CoreCmsOrderLog
                                    {
                                        userId = model.userId,
                                        orderId = model.orderId,
                                        type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_CREATE,
                                        msg = "发货",
                                        data = JsonConvert.SerializeObject(model),
                                        createTime = DateTime.Now,
                                        userName = _user.nickName,
                                        number = string.Empty
                                    };
                                 jm.code=await _coreCmsOrderLogServices.InsertAsync(orderLog);
                                    jm.msg = "发货成功";
                                    await _coreCmsStockLogServices.InsertAsync(stockLogs);
                                    //await _coreCmsStockServices.InsertAsync(stock);

                                }
                            }
                            else
                            {
                                users.Add(new CoreCmsOrder { orderId = orderId });
                            }
                        }
                        
                        //var orderLog = new CoreCmsOrderLog
                        //{
                        //    userId = entity.userId,
                        //    orderId = oldModel.orderId,
                        //    type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_CREATE,
                        //    msg = "编辑资料",
                        //    data = JsonConvert.SerializeObject(oldModel),
                        //    createTime = DateTime.Now,
                        //    userName = _user.nickName,
                        //    number = entity.number
                        //};
                        //users.Add(new CoreCmsOrder { nickName = name, id = age });

                    }
                }
            }

            jm.data = users;


            return jm;
        }

        #region 跟进客查询户编号============================================================
        // POST: Api/CoreCmsOrder/AddGetByNumber
        /// <summary>
        /// 跟进客查询户编号
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("跟进客查询户编号")]
        public async Task<AdminUiCallBack> AddGetByNumber([FromBody] FMIntId entity)
        {
            //返回数据
            var jm = new AdminUiCallBack();

            var model = await _userServices.QueryByClauseAsync(p => p.number == entity.number);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }

            jm.code = 0;
            var classList = await _coreCmsCustomerClassServices.QueryAsync();//客户分类
            var sourceList = await _coreCmsSourceServices.QueryAsync();//来源
            var orderTypeList = await _coreCmsOrderTypeServices.QueryAsync();//订单类型
            var wxNumberList = await _coreCmsWechatnumberServices.QueryAsync();//归属微信号
            var customerGroupList = await _coreCmsCustomerGroupServices.QueryAsync();//群体
            var sexTypes = EnumHelper.EnumToList<GlobalEnumVars.UserSexTypes>();
            var userStatus = EnumHelper.EnumToList<GlobalEnumVars.UserStatus>();
            var uuserList=await _sysUserServices.QueryAsync();
            var newPaymentsList=EnumHelper.EnumToList<GlobalEnumVars.NewPaymentsTypes>();//支付方式
            var orderTypeCRMList = EnumHelper.EnumToList<GlobalEnumVars.OrderTypeCrm>();//订单类型
            //var collectingList= EnumHelper.EnumToList<GlobalEnumVars.CollectingTypes>();//代收方式
            // var userGrade = await _coreCmsUserGradeServices.QueryAsync(false, true);

            jm.data = new
            {
                model,
                classList,
                sourceList,
                sexTypes,
                userStatus,
                uuserList,
                newPaymentsList,
                orderTypeCRMList
            };

            return jm;
        }
        #endregion



        #region 编辑数据============================================================
        // POST: Api/CoreCmsOrder/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();
            var newPaymentsList = EnumHelper.EnumToList<GlobalEnumVars.NewPaymentsTypes>();//支付方式
            var orderTypeCRMList = EnumHelper.EnumToList<GlobalEnumVars.OrderTypeCrm>();//订单类型
            var storeList = await _storeServices.QueryAsync();
            var result = await _coreCmsOrderServices.GetOrderInfoByOrderId(entity.id);
            if (!result.status)
            {
                jm.msg = result.msg;
                return jm;
            }
            jm.code = 0;
            jm.data = new
            {
                orderModel = result.data,
                storeList,
                newPaymentsList,
                orderTypeCRMList
            };

            return jm;
        }
        #endregion

        #region 编辑数据订单============================================================
        // POST: Api/CoreCmsOrder/GetEdit
        /// <summary>
        /// 编辑数据订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据订单")]
        public async Task<AdminUiCallBack> GetEditOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();
            var newPaymentsList = EnumHelper.EnumToList<GlobalEnumVars.NewPaymentsTypes>();//支付方式
            var orderTypeCRMList = EnumHelper.EnumToList<GlobalEnumVars.OrderTypeCrm>();//订单类型
            var uuserList = await _sysUserServices.QueryAsync();//归属销售
            var storeList = await _storeServices.QueryAsync();
            var result = await _coreCmsOrderServices.GetOrderInfoByOrderId(entity.id);

            if (!result.status)
            {
                jm.msg = result.msg;
                return jm;
            }
            jm.code = 0;
            jm.data = new
            {
                model = result.data,
                storeList,
                newPaymentsList,
                orderTypeCRMList,
                uuserList
            };

            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Admins/CoreCmsOrder/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody] AdminEditOrderPost entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsOrderServices.QueryByClauseAsync(p=>p.orderId==entity.orderId);
            var orderLog = new CoreCmsOrderLog
            {
                userId = entity.userId,
                orderId = oldModel.orderId,
                type = (int)GlobalEnumVars.OrderLogTypes.LOG_TYPE_CREATE,
                msg = "编辑资料",
                data = JsonConvert.SerializeObject(oldModel),
                createTime = DateTime.Now,
                userName = _user.nickName,
                number = entity.number
            };
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.sysid = entity.sysid;
            oldModel.mark = entity.mark;
            //事物处理过程开始
            if (entity.paymentCode=="货到付款")
            {
                oldModel.collectingName = "代收";
            }
            else
            {
                oldModel.collectingName = "不代收";
            }
            oldModel.paymentCode=entity.paymentCode;
            oldModel.orderTypeName= entity.orderTypeName;
            oldModel.shipMobile = entity.shipMobile;
            oldModel.shipName = entity.shipName;
            if (oldModel.orderAmount != entity.orderAmount)
            {
                oldModel.orderAmount = entity.orderAmount;
            }
            if (entity.payedAmount>0)
            {
                oldModel.payedAmount = entity.payedAmount;
            }
            if (entity.goodsAmount > 0)
            {
                oldModel.goodsAmount = entity.goodsAmount;
            }
            if (!string.IsNullOrEmpty(entity.newshipAddress))
            {
               // var newshipAddress = entity.newshipAddress.Replace(" ","");
                oldModel.shipAddress = entity.newshipAddress.Replace(" ", "");
            }

           
            //事物处理过程结束
            var bl = await _coreCmsOrderServices.UpdateAsync(oldModel);
            if (bl == true)
            {
                var userModel = await _userServices.QueryByClauseAsync(p=>p.number==entity.number);
                if (userModel.id>0)
                {
                     await _userServices.UpdateAsync(p => new CoreCmsUser() { sysid=entity.sysid }, p => p.id == userModel.id);

                }
                await _coreCmsOrderLogServices.InsertAsync(orderLog);


            }
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 发货============================================================
        // POST: Api/CoreCmsOrder/GetShip
        /// <summary>
        /// 发货
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("发货")]
        public async Task<AdminUiCallBack> GetShip([FromBody] FMArrayStringIds entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.id.Length == 0)
            {
                jm.msg = "请选择需要发货的数据";
                return jm;
            }



            var storeList = await _storeServices.QueryAsync();

            var logistics = await _logisticsServices.QueryListByClauseAsync(p => p.isDelete == false);
            var deliveryCompany = await _weChatShippingDeliveryServices.GetCaChe();
            var result = await _coreCmsOrderServices.GetOrderShipInfo(entity.id);
            if (!result.status)
            {
                jm.msg = result.msg;
                return jm;
            }

            if (storeList.Any())
            {
                foreach (var store in storeList)
                {
                    var getfullName = await _areaServices.GetAreaFullName(store.areaId);
                    if (getfullName.status)
                    {
                        store.allAddress = getfullName.data + store.address;
                    }
                }
            }
            jm.code = 0;
            jm.msg = result.msg;
            jm.data = new
            {
                orderModel = result.data,
                deliveryCompany,
                storeList,
                logistics,
            };

            return jm;
        }
        #endregion

        #region 发货提交============================================================
        // POST: Admins/CoreCmsOrder/Edit
        /// <summary>
        /// 发货提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("发货提交")]
        public async Task<AdminUiCallBack> DoShip([FromBody] AdminOrderShipPost entity)
        {
            var jm = new AdminUiCallBack();

            WebApiCallBack result;
            if (entity.orderId.Contains(","))
            {
                var ids = entity.orderId.Split(",");
                result = await _coreCmsOrderServices.BatchShip(ids, entity.logiCode, entity.logiNo, entity.items, entity.shipName, entity.shipMobile, entity.shipAddress, entity.memo, entity.storeId, entity.shipAreaId, entity.deliveryCompanyId);

                if (result.status)
                {
                    var orderPaymentIds = await _billPaymentsServices.QueryListByClauseAsync(p => ids.Contains(p.sourceId) && p.paymentCode == GlobalEnumVars.PaymentsTypes.wechatpay.ToString() && p.status == (int)GlobalEnumVars.BillPaymentsStatus.Payed);
                    if (orderPaymentIds.Any())
                    {
                        //依次推入队列.
                        foreach (var item in orderPaymentIds)
                        {
                            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.WeChatPayShipping, item.paymentId);
                        }
                    }

                }

            }
            else
            {
                result = await _coreCmsOrderServices.Ship(entity.orderId, entity.logiCode, entity.logiNo, entity.items, entity.shipName, entity.shipMobile, entity.shipAddress, entity.memo, entity.storeId, entity.shipAreaId, entity.deliveryCompanyId);

                //微信发货信息管理API发货
                if (result.status && await _billPaymentsServices.QueryByClauseAsync(p => p.sourceId == entity.orderId && p.status == (int)GlobalEnumVars.BillPaymentsStatus.Payed) is { } paymentInfo)
                {
                    await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.WeChatPayShipping, paymentInfo.paymentId);
                }

            }

            jm.code = result.status ? 0 : 1;
            jm.msg = result.msg;
            jm.data = result.data;
            jm.otherData = entity;

            return jm;
        }
        #endregion

        #region 秒发货============================================================
        // POST: Admins/CoreCmsOrder/Edit
        /// <summary>
        /// 秒发货
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("秒发货")]
        public async Task<AdminUiCallBack> DoSecondsShip([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var order = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (order == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }

            var goodItems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == entity.id);
            if (!goodItems.Any())
            {
                jm.msg = "明细获取失败";
                return jm;
            }

            Dictionary<int, int> items = new Dictionary<int, int>();

            goodItems.ForEach(p =>
            {
                items.Add(p.productId, p.nums);
            });

            var result = new WebApiCallBack();

            if (order.receiptType == (int)GlobalEnumVars.OrderReceiptType.SelfDelivery)
            {
                result = await _coreCmsOrderServices.Ship(order.orderId, "shangmenziti", "无", items, order.shipName, order.shipMobile, order.shipAddress, order.memo, order.storeId, order.shipAreaId, "OTHERS");
            }
            else if (order.receiptType == (int)GlobalEnumVars.OrderReceiptType.IntraCityService)
            {
                result = await _coreCmsOrderServices.Ship(order.orderId, "benditongcheng", "无", items, order.shipName, order.shipMobile, order.shipAddress, order.memo, order.storeId, order.shipAreaId, "OTHERS");
            }

            //微信发货信息管理API发货
            if (result.status && await _billPaymentsServices.QueryByClauseAsync(p => p.sourceId == order.orderId && p.status == (int)GlobalEnumVars.BillPaymentsStatus.Payed) is { } paymentInfo)
            {
                await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.WeChatPayShipping, paymentInfo.paymentId);
            }

            jm.code = result.status ? 0 : 1;
            jm.msg = result.msg;
            jm.data = result.data;
            jm.otherData = entity;

            return jm;
        }
        #endregion

        #region 支付============================================================
        // POST: Api/CoreCmsOrder/GetPay
        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("支付")]
        public async Task<AdminUiCallBack> GetPay([FromBody] FMArrayStringIds entity)
        {
            var jm = new AdminUiCallBack();

            var type = entity.data.ObjectToInt();
            if (type == 0 || entity.id.Length == 0)
            {
                jm.msg = "请提交合法的数据";
                return jm;
            }

            var result = await _billPaymentsServices.BatchFormatPaymentRel(entity.id, type, null);
            if (result.status == false)
            {
                jm.msg = result.msg;
                jm.data = result.data;
                return jm;
            }
            //取支付方式
            var payments = await _paymentsServices.QueryListByClauseAsync(p => p.isEnable, p => p.sort, OrderByType.Asc);
            jm.code = 0;
            jm.msg = "获取数据成功";
            jm.data = new
            {
                orderId = entity.id,
                type = entity.data,
                payments,
                rel = result.data
            };

            return jm;
        }
        #endregion

        #region 提交支付============================================================
        // POST: Admins/CoreCmsOrder/DoToPay
        /// <summary>
        /// 提交支付
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("提交支付")]
        public async Task<AdminUiCallBack> DoToPay([FromBody] AdminOrderDoPayPost entity)
        {
            var jm = new AdminUiCallBack();

            //事物处理过程结束
            var ids = entity.orderId.Split(",");
            var result = await _billPaymentsServices.ToPay(entity.orderId, entity.type, entity.paymentCode);

            jm.code = result.status ? 0 : 1;
            jm.msg = result.msg;

            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            //假删除
            var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { isdel = true }, p => p.orderId == model.orderId);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.DeleteSuccess : GlobalConstVars.DeleteFailure;
            return jm;

        }
        #endregion
        #region 删除产品数据============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 删除产品数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("删除产品数据")]
        public async Task<AdminUiCallBack> DoDeleteProduct([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _orderItemServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            var fl = await _orderItemServices.DeleteByIdAsync(entity.id);
            if (fl==true)
            {
                jm.code = 0;
                jm.msg = "删除成功";

            }
            return jm;

        }
        #endregion
        #region 确认订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 确认订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("确认订单")]
        public async Task<AdminUiCallBack> ConfirmOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status==1)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status = 4 }, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code==0)
                {
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = model.userId,
                        orderId =model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "确认订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number =model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #endregion
        #region 批准订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 批准订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("批准订单")]
        public async Task<AdminUiCallBack> ApproveOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status ==4)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status = 5 }, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code == 0)
                {
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = model.userId,
                        orderId = model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "批准订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number = model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #region 发货订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 发货订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("发货订单")]
        public async Task<AdminUiCallBack> SendOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status == 5)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status =6 }, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code == 0)
                {
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = model.userId,
                        orderId = model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "发货订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number = model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #endregion

        #region 已签收订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 已签收订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("已签收订单")]
        public async Task<AdminUiCallBack> SignedOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status ==6)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status =8, signTime=DateTime.Now }, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code == 0)
                {
                    var userModel=await _coreCmsUserServices.QueryByIdAsync(model.userId);
                    userModel.orderNumber +=1;
                    userModel.amount += model.orderAmount;
                    //更新次数
                    await _coreCmsUserServices.UpdateAsync(p=>new CoreCmsUser() { orderNumber=userModel.orderNumber,amount=userModel.amount, signforDivideTime=DateTime.Now}, p=>p.id==model.userId );
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {

                        userId = model.userId,
                        orderId = model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "已签收订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number = model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #endregion

        #region 退货订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 退货订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("退货订单")]
        public async Task<AdminUiCallBack> CancelOrderInfo([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status == 6)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status =9}, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code == 0)
                {
                    var userModel = await _coreCmsUserServices.QueryByIdAsync(model.userId);
                    userModel.orderNumber = userModel.orderNumber-1;
                    userModel.amount = userModel.amount-model.orderAmount;
                    //更新次数
                    await _coreCmsUserServices.UpdateAsync(p => new CoreCmsUser() { orderNumber = userModel.orderNumber, amount = userModel.amount, signforDivideTime = DateTime.Now }, p => p.id == model.userId);
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = model.userId,
                        orderId = model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "退货订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number = model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #endregion


        #region 入库订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 入库订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("入库订单")]
        public async Task<AdminUiCallBack> WarehouseOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status == 9)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status = 10 }, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code == 0)
                {
                    var stockLogs = new List<CoreCmsStockLog>();
                    jm.code = 0;
                    var productList = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == model.orderId);
                    if (productList.Count > 0)
                    {

                        foreach (var item in productList)
                        {
                            //  _coreCmsGoodsServices.uo(CoreCmsProducts)
                            int count = await _coreCmsGoodsServices.NewChangeStock(item.productId, "store", item.nums);
                            var sLog = new CoreCmsStockLog
                            {
                                stockId = item.orderId,
                                productId = item.productId,
                                goodsId = item.goodsId,
                                nums = +item.nums,
                                sn = item.sn,
                                bn = string.Empty,
                                goodsName = item.name,
                                spesDesc = item.addon,
                                fcreateTime = DateTime.Now

                            };
                            stockLogs.Add(sLog);
                        }
                        await _coreCmsStockLogServices.InsertAsync(stockLogs);

                    }
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = model.userId,
                        orderId = model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "入库订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number = model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #endregion
        #region 完成订单============================================================
        // POST: Api/CoreCmsOrder/DoDelete/10
        /// <summary>
        /// 完成订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("完成订单")]
        public async Task<AdminUiCallBack> CompleteOrder([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            if (model.status == 8)
            {
                //更新状态
                var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { status = 2,completeTime=DateTime.Now }, p => p.orderId == model.orderId);
                jm.code = bl ? 0 : 1;
                if (jm.code == 0)
                {
                    //订单记录
                    var orderLog = new CoreCmsOrderLog
                    {
                        userId = model.userId,
                        orderId = model.orderId,
                        type = (int)GlobalEnumVars.OrderLogTypes.Confirm,
                        msg = "完成订单",
                        data = JsonConvert.SerializeObject(model),
                        createTime = DateTime.Now,
                        userName = _user.nickName,
                        number = model.number
                    };
                    await _coreCmsOrderLogServices.InsertAsync(orderLog);
                }
                jm.msg = bl ? "操作成功" : "操作失败";
            }
            else
            {
                jm.msg = "确认订单失败";
            }

            return jm;

        }
        #endregion
        #endregion
        #region 还原订单============================================================
        // POST: Api/CoreCmsOrder/DoRestore/10
        /// <summary>
        /// 还原订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("还原订单")]
        public async Task<AdminUiCallBack> DoRestore([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (model == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            //还原
            var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { isdel = false }, p => p.orderId == model.orderId);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;
            return jm;

        }
        #endregion

        #region 判断是否存在售后============================================================
        // POST: Api/CoreCmsOrder/GetDoHaveAfterSale/10
        /// <summary>
        /// 判断是否存在售后
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("判断是否存在售后")]
        public async Task<AdminUiCallBack> GetDoHaveAfterSale([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            //等待售后审核的订单，不自动操作完成。
            var billAftersalesCount = await _aftersalesServices.GetCountAsync(p => p.orderId == entity.id && p.status == (int)GlobalEnumVars.BillAftersalesStatus.WaitAudit);

            bool bl = billAftersalesCount > 0;

            jm.code = bl ? 0 : 1;
            jm.msg = "存在未处理的售后";

            return jm;

        }
        #endregion

        #region 完成订单============================================================
        // POST: Api/CoreCmsOrder/DoComplete/10
        /// <summary>
        /// 完成订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("完成订单")]
        public async Task<AdminUiCallBack> DoComplete([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var result = await _coreCmsOrderServices.CompleteOrder(entity.id);
            jm.code = result.status ? 0 : 1;
            jm.msg = result.msg;
            jm.data = result.data;
            jm.otherData = result.otherData;

            return jm;

        }
        #endregion

        #region 预览数据============================================================
        // POST: Api/CoreCmsOrder/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();
           
            var result = await _coreCmsOrderServices.GetOrderInfoByOrderId(entity.id);
            //var model = await _coreCmsOrderServices.QueryByClauseAsync(p=>p.orderId==entity.id);
            if (result == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
          
            jm.code = result.status ? 0 : 1;
            jm.data = result.data;

            return jm;
        }
        #endregion

        #region 重打小票============================================================
        // POST: Api/CoreCmsOrder/GetPrintTpl/10
        /// <summary>
        /// 重打小票
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("重打小票")]
        public async Task<AdminUiCallBack> GetPrintCloud([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var order = await _coreCmsOrderServices.QueryByClauseAsync(p => p.orderId == entity.id);
            if (order == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }

            //易联云打印机打印
            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.OrderPrint, JsonConvert.SerializeObject(order));

            jm.code = 0;
            jm.msg = "提交打印队列成功";

            return jm;
        }
        #endregion

        #region 订单打印============================================================
        // POST: Api/CoreCmsOrder/GetPrintTpl/10
        /// <summary>
        /// 订单打印
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("订单打印")]
        public async Task<AdminUiCallBack> GetPrintTpl([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var result = await _coreCmsOrderServices.GetOrderInfoByOrderId(entity.id);
            if (result == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = result.status ? 0 : 1;


            var allConfigs = await _settingServices.GetConfigDictionaries();

            var shopName = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShopName);
            var shopMobile = CommonHelper.GetConfigDictionary(allConfigs, SystemSettingConstVars.ShopMobile);

            jm.data = new
            {
                order = result.data,
                shopName,
                shopMobile
            };

            return jm;
        }
        #endregion

        #region 选择导出============================================================
        // POST: Api/CoreCmsOrder/SelectExportExcel/10
        /// <summary>
        /// 选择导出
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("选择导出")]
        public async Task<AdminUiCallBack> SelectExportExcel([FromBody] FMArrayStringIds entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.id.Length == 0)
            {
                jm.msg = "请选择要导出的数据";
                return jm;
            }


            //获取数据
            var list = await _coreCmsOrderServices.QueryListAsync(p => entity.id.Contains(p.orderId), p => p.createTime, OrderByType.Desc);
            if (list != null && list.Any())
            {
                var areaCache = await _areaServices.GetCaChe();
                foreach (var item in list)
                {
                    //item.operating = _coreCmsOrderServices.GetOperating(item.orderId, item.status, item.payStatus, item.shipStatus, item.isdel);
                    //item.afterSaleStatus = "";
                    //if (item.aftersalesItem != null && item.aftersalesItem.Any())
                    //{
                    //    foreach (var sale in item.aftersalesItem)
                    //    {
                    //        item.afterSaleStatus += EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillAftersalesStatus>(sale.status) + "<br>";
                    //    }
                    //}
                    var areas = await _areaServices.GetAreaFullName(item.shipAreaId, areaCache);
                    item.shipAreaName = areas.status ? areas.data + "-" + item.shipAddress : item.shipAddress;
                }
            }


            //订单状态说明
            var orderStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderStatusDescription>();
            //付款状态
            var orderPayStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderPayStatus>();
            //发货状态
            var shipStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderShipStatus>();
            //订单来源
            var sourceEntities = EnumHelper.EnumToList<GlobalEnumVars.Source>();
            //订单类型
            var orderTypeEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderType>();
            //订单支付方式
            var paymentsTypesEntities = EnumHelper.EnumToList<GlobalEnumVars.PaymentsTypes>();
            //收货状态
            var orderConfirmStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderConfirmStatus>();
            //订单收货方式
            var orderReceiptTypeEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderReceiptType>();


            //获取数据
            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var sheet1 = book.CreateSheet("Sheet1");

            //获取list数据
            //给sheet1添加第一行的头部标题
            var row1 = sheet1.CreateRow(0);

            var items = new List<CellValueItem>();
            items.Add(new CellValueItem() { name = "序号", width = 10 });
            items.Add(new CellValueItem() { name = "订单号", width = 20 });
            items.Add(new CellValueItem() { name = "商品总价", width = 12 });
            items.Add(new CellValueItem() { name = "支付金额", width = 12 });
            items.Add(new CellValueItem() { name = "订单总额", width = 12 });
            items.Add(new CellValueItem() { name = "支付状态", width = 12 });
            items.Add(new CellValueItem() { name = "发货状态", width = 12 });
            items.Add(new CellValueItem() { name = "订单状态", width = 12 });
            items.Add(new CellValueItem() { name = "订单类型", width = 12 });
            items.Add(new CellValueItem() { name = "支付方式", width = 12 });
            items.Add(new CellValueItem() { name = "支付时间", width = 20 });

            items.Add(new CellValueItem() { name = "货品名称", width = 50 });
            items.Add(new CellValueItem() { name = "数量", width = 12 });
            items.Add(new CellValueItem() { name = "单价", width = 12 });
            items.Add(new CellValueItem() { name = "优惠", width = 12 });
            items.Add(new CellValueItem() { name = "合计", width = 12 });


            items.Add(new CellValueItem() { name = "收货人姓名", width = 12 });
            items.Add(new CellValueItem() { name = "收货电话", width = 12 });
            items.Add(new CellValueItem() { name = "收货详细地址", width = 80 });


            items.Add(new CellValueItem() { name = "配送方式名称", width = 20 });
            items.Add(new CellValueItem() { name = "配送费用", width = 12 });
            items.Add(new CellValueItem() { name = "用户ID", width = 12 });

            items.Add(new CellValueItem() { name = "是否收货", width = 20 });
            items.Add(new CellValueItem() { name = "确认收货时间", width = 20 });


            items.Add(new CellValueItem() { name = "商品总重量", width = 20 });
            items.Add(new CellValueItem() { name = "是否开发票", width = 20 });
            items.Add(new CellValueItem() { name = "税号", width = 20 });
            items.Add(new CellValueItem() { name = "发票抬头", width = 20 });
            items.Add(new CellValueItem() { name = "使用积分", width = 20 });
            items.Add(new CellValueItem() { name = "积分抵扣金额", width = 20 });
            items.Add(new CellValueItem() { name = "订单优惠金额", width = 20 });
            items.Add(new CellValueItem() { name = "商品优惠金额", width = 20 });
            items.Add(new CellValueItem() { name = "优惠券优惠额度", width = 20 });
            items.Add(new CellValueItem() { name = "优惠券信息", width = 20 });
            items.Add(new CellValueItem() { name = "优惠信息", width = 20 });
            items.Add(new CellValueItem() { name = "买家备注", width = 20 });
            items.Add(new CellValueItem() { name = "下单IP", width = 20 });
            items.Add(new CellValueItem() { name = "卖家备注", width = 20 });
            items.Add(new CellValueItem() { name = "订单来源", width = 20 });
            items.Add(new CellValueItem() { name = "是否评论", width = 20 });
            items.Add(new CellValueItem() { name = "删除标志", width = 20 });
            items.Add(new CellValueItem() { name = "订单时间", width = 20 });
            items.Add(new CellValueItem() { name = "更新时间", width = 20 });

            var headerStyle = ExcelHelper.GetHeaderStyle(book);

            for (int i = 0; i < items.Count; i++)
            {
                var cell = row1.CreateCell(i);
                cell.SetCellValue(items[i].name);
                cell.CellStyle = headerStyle;
                sheet1.SetColumnWidth(i, items[i].width * 256);
            }

            row1.Height = 30 * 20;

            var commonCellStyle = ExcelHelper.GetCommonStyle(book);


            var detailsStartNumber = 0;
            var listStartNumber = 0;
            foreach (var order in list)
            {
                listStartNumber++;
                //当前开始行
                var nowNumber = detailsStartNumber;
                //将数据逐步写入sheet1各个行
                foreach (var t in order.items)
                {
                    var rowTemp = sheet1.CreateRow(detailsStartNumber + 1);

                    rowTemp.CreateCell(0).SetCellValue(listStartNumber);
                    rowTemp.CreateCell(1).SetCellValue(order.orderId);
                    rowTemp.CreateCell(2).SetCellValue(order.goodsAmount.ToString());
                    rowTemp.CreateCell(3).SetCellValue(order.payedAmount.ToString());
                    rowTemp.CreateCell(4).SetCellValue(order.orderAmount.ToString());

                    var payModel = orderPayStatusEntities.Find(p => p.value == order.payStatus);
                    rowTemp.CreateCell(5).SetCellValue(payModel != null ? payModel.description : "");

                    var shipStatusModel = shipStatusEntities.Find(p => p.value == order.shipStatus);
                    rowTemp.CreateCell(6).SetCellValue(shipStatusModel != null ? shipStatusModel.description : "");

                    var statusModel = orderStatusEntities.Find(p => p.value == order.status);
                    rowTemp.CreateCell(7).SetCellValue(statusModel != null ? statusModel.description : "");

                    var orderTypeModel = orderTypeEntities.Find(p => p.value == order.orderType);
                    rowTemp.CreateCell(8).SetCellValue(orderTypeModel != null ? orderTypeModel.description : "");

                    var paymentCodeModel = paymentsTypesEntities.Find(p => p.title == order.paymentCode);
                    rowTemp.CreateCell(9).SetCellValue(paymentCodeModel != null ? paymentCodeModel.description : "");

                    rowTemp.CreateCell(10).SetCellValue(order.paymentTime.ToString());


                    rowTemp.CreateCell(11).SetCellValue(!string.IsNullOrEmpty(t.addon) ? t.name + "【" + t.goodsId + "】规格：" + t.addon : "【" + t.goodsId + "】" + t.name);
                    rowTemp.CreateCell(12).SetCellValue(t.nums);
                    rowTemp.CreateCell(13).SetCellValue(t.price + "元");
                    rowTemp.CreateCell(14).SetCellValue(t.promotionAmount + "元");
                    rowTemp.CreateCell(15).SetCellValue(t.amount + "元");


                    rowTemp.CreateCell(16).SetCellValue(order.shipName);
                    rowTemp.CreateCell(17).SetCellValue(order.shipMobile);
                    rowTemp.CreateCell(18).SetCellValue(order.shipAreaName);

                    rowTemp.CreateCell(19).SetCellValue(!string.IsNullOrEmpty(order.logisticsName) ? order.logisticsName : "自提配送");
                    rowTemp.CreateCell(20).SetCellValue(order.costFreight.ToString());
                    rowTemp.CreateCell(21).SetCellValue(order.userId.ToString());

                    var confirmStatusModel = orderConfirmStatusEntities.Find(p => p.value == order.confirmStatus);
                    rowTemp.CreateCell(22).SetCellValue(confirmStatusModel != null ? confirmStatusModel.description : "");

                    rowTemp.CreateCell(23).SetCellValue(order.confirmTime.ToString());

                    rowTemp.CreateCell(24).SetCellValue(order.weight.ToString());
                    rowTemp.CreateCell(25).SetCellValue(order.taxType.ToString());
                    rowTemp.CreateCell(26).SetCellValue(order.taxCode);
                    rowTemp.CreateCell(27).SetCellValue(order.taxTitle);
                    rowTemp.CreateCell(28).SetCellValue(order.point.ToString());
                    rowTemp.CreateCell(29).SetCellValue(order.pointMoney.ToString());
                    rowTemp.CreateCell(30).SetCellValue(order.orderDiscountAmount.ToString());
                    rowTemp.CreateCell(31).SetCellValue(order.goodsDiscountAmount.ToString());
                    rowTemp.CreateCell(32).SetCellValue(order.couponDiscountAmount.ToString());
                    rowTemp.CreateCell(33).SetCellValue(order.coupon);
                    rowTemp.CreateCell(34).SetCellValue(order.promotionList);
                    rowTemp.CreateCell(35).SetCellValue(order.memo);
                    rowTemp.CreateCell(36).SetCellValue(order.ip);
                    rowTemp.CreateCell(37).SetCellValue(order.mark);
                    rowTemp.CreateCell(38).SetCellValue(order.source.ToString());
                    rowTemp.CreateCell(39).SetCellValue(order.isComment.ToString());
                    rowTemp.CreateCell(40).SetCellValue(order.isdel.ToString());
                    rowTemp.CreateCell(41).SetCellValue(order.createTime.ToString());
                    rowTemp.CreateCell(42).SetCellValue(order.updateTime.ToString());


                    rowTemp.Cells.ForEach(p =>
                    {
                        p.CellStyle = commonCellStyle;
                    });
                    rowTemp.Height = 20 * 20;


                    detailsStartNumber++;
                }
                //合并单元格（第几行，到第几行，第几列，到第几列）

                var marId = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
                if (order.items.Count <= 1) continue;
                foreach (var id in marId)
                {
                    sheet1.AddMergedRegion(new CellRangeAddress(nowNumber + 1, detailsStartNumber, id, id));
                }
            }

            // 写入到excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-订单导出(选择结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        #region 查询导出============================================================
        // POST: Api/CoreCmsOrder/QueryExportExcel/10
        /// <summary>
        /// 查询导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("查询导出")]
        public async Task<AdminUiCallBack> QueryExportExcel()
        {

            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsOrder>();
            //获取排序字段

            //订单号 nvarchar
            var orderId = Request.Form["orderId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(orderId))
            {
                where = where.And(p => p.orderId.Contains(orderId));
            }

            //订单状态 int
            var status = Request.Form["status"].FirstOrDefault().ObjectToInt(0);
            if (status > 0)
            {
                where = where.And(p => p.status == status);
            }
            //订单类型 int
            var orderType = Request.Form["orderType"].FirstOrDefault().ObjectToInt(0);
            if (orderType > 0)
            {
                where = where.And(p => p.orderType == orderType);
            }
            //发货状态 int
            var shipStatus = Request.Form["shipStatus"].FirstOrDefault().ObjectToInt(0);
            if (shipStatus > 0)
            {
                where = where.And(p => p.shipStatus == shipStatus);
            }
            //支付状态 int
            var payStatus = Request.Form["payStatus"].FirstOrDefault().ObjectToInt(0);
            if (payStatus > 0)
            {
                where = where.And(p => p.payStatus == payStatus);
            }
            //支付方式代码 nvarchar
            var paymentCode = Request.Form["paymentCode"].FirstOrDefault();
            if (!string.IsNullOrEmpty(paymentCode))
            {
                where = where.And(p => p.paymentCode.Contains(paymentCode));
            }
            //售后状态 int
            var confirmStatus = Request.Form["confirmStatus"].FirstOrDefault().ObjectToInt(0);
            if (confirmStatus > 0)
            {
                where = where.And(p => p.confirmStatus == confirmStatus);
            }
            //订单来源 int
            var source = Request.Form["source"].FirstOrDefault().ObjectToInt(0);
            if (source > 0)
            {
                where = where.And(p => p.source == source);
            }
            //收货方式 int
            var receiptType = Request.Form["receiptType"].FirstOrDefault().ObjectToInt(0);
            if (receiptType > 0)
            {
                where = where.And(p => p.receiptType == receiptType);
            }

            //收货人姓名 nvarchar
            var shipName = Request.Form["shipName"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipName))
            {
                where = where.And(p => p.shipName.Contains(shipName));
            }
            //收货人地址 nvarchar
            var shipAddress = Request.Form["shipAddress"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipAddress))
            {
                where = where.And(p => p.shipAddress.Contains(shipAddress));
            }

            //收货电话 nvarchar
            var shipMobile = Request.Form["shipMobile"].FirstOrDefault();
            if (!string.IsNullOrEmpty(shipMobile))
            {
                where = where.And(p => p.shipMobile.Contains(shipMobile));
            }

            //付款单号 nvarchar
            var paymentId = Request.Form["paymentId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(paymentId))
            {
                where = where.And(p => p.shipMobile.Contains(paymentId));
            }

            // datetime
            var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }


            //订单状态 int
            var orderUnifiedStatus = ObjectExtensions.ObjectToInt(Request.Form["orderUnifiedStatus"].FirstOrDefault(), 0);
            if (orderUnifiedStatus > 0)
            {
                if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.payment)
                {
                    //待支付
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_PAYMENT));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.delivered)
                {
                    //待发货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_DELIVERY));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.receive)
                {
                    //待收货
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_RECEIPT));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.evaluated)
                {
                    //已评价
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_COMPLETED_EVALUATE));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.noevaluat)
                {
                    //待评价
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_PENDING_EVALUATE));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.complete)
                {
                    //已完成
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_COMPLETED));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.cancel)
                {
                    //已取消
                    where = where.And(_coreCmsOrderServices.GetReverseStatus((int)GlobalEnumVars.OrderAllStatusType.ALL_CANCEL));
                }
                else if (orderUnifiedStatus == (int)GlobalEnumVars.OrderCountType.delete)
                {
                    //已取消
                    where = where.And(p => p.isdel == true);
                }
            }
            else
            {
                where = where.And(p => p.isdel == false);
            }

            //获取数据
            var list = await _coreCmsOrderServices.QueryListAsync(where, p => p.createTime, OrderByType.Desc);
            if (list != null && list.Any())
            {
                var areaCache = await _areaServices.GetCaChe();
                foreach (var item in list)
                {
                    //item.operating = _coreCmsOrderServices.GetOperating(item.orderId, item.status, item.payStatus, item.shipStatus, item.isdel);
                    //item.afterSaleStatus = "";
                    //if (item.aftersalesItem != null && item.aftersalesItem.Any())
                    //{
                    //    foreach (var sale in item.aftersalesItem)
                    //    {
                    //        item.afterSaleStatus += EnumHelper.GetEnumDescriptionByValue<GlobalEnumVars.BillAftersalesStatus>(sale.status) + "<br>";
                    //    }
                    //}
                    var areas = await _areaServices.GetAreaFullName(item.shipAreaId, areaCache);
                    item.shipAreaName = areas.status ? areas.data + "-" + item.shipAddress : item.shipAddress;
                }
            }


            //订单状态说明
            var orderStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderStatusDescription>();
            //付款状态
            var orderPayStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderPayStatus>();
            //发货状态
            var shipStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderShipStatus>();
            //订单来源
            var sourceEntities = EnumHelper.EnumToList<GlobalEnumVars.Source>();
            //订单类型
            var orderTypeEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderType>();
            //订单支付方式
            var paymentsTypesEntities = EnumHelper.EnumToList<GlobalEnumVars.PaymentsTypes>();
            //收货状态
            var orderConfirmStatusEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderConfirmStatus>();
            //订单收货方式
            var orderReceiptTypeEntities = EnumHelper.EnumToList<GlobalEnumVars.OrderReceiptType>();


            //获取数据
            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var sheet1 = book.CreateSheet("Sheet1");

            //获取list数据
            //给sheet1添加第一行的头部标题
            var row1 = sheet1.CreateRow(0);

            var items = new List<CellValueItem>();
            items.Add(new CellValueItem() { name = "序号", width = 10 });
            items.Add(new CellValueItem() { name = "订单号", width = 20 });
            items.Add(new CellValueItem() { name = "商品总价", width = 12 });
            items.Add(new CellValueItem() { name = "支付金额", width = 12 });
            items.Add(new CellValueItem() { name = "订单总额", width = 12 });
            items.Add(new CellValueItem() { name = "支付状态", width = 12 });
            items.Add(new CellValueItem() { name = "发货状态", width = 12 });
            items.Add(new CellValueItem() { name = "订单状态", width = 12 });
            items.Add(new CellValueItem() { name = "订单类型", width = 12 });
            items.Add(new CellValueItem() { name = "支付方式", width = 12 });
            items.Add(new CellValueItem() { name = "支付时间", width = 20 });

            items.Add(new CellValueItem() { name = "货品名称", width = 50 });
            items.Add(new CellValueItem() { name = "数量", width = 12 });
            items.Add(new CellValueItem() { name = "单价", width = 12 });
            items.Add(new CellValueItem() { name = "优惠", width = 12 });
            items.Add(new CellValueItem() { name = "合计", width = 12 });


            items.Add(new CellValueItem() { name = "收货人姓名", width = 12 });
            items.Add(new CellValueItem() { name = "收货电话", width = 12 });
            items.Add(new CellValueItem() { name = "收货详细地址", width = 80 });


            items.Add(new CellValueItem() { name = "配送方式名称", width = 20 });
            items.Add(new CellValueItem() { name = "配送费用", width = 12 });
            items.Add(new CellValueItem() { name = "用户ID", width = 12 });

            items.Add(new CellValueItem() { name = "是否收货", width = 20 });
            items.Add(new CellValueItem() { name = "确认收货时间", width = 20 });


            items.Add(new CellValueItem() { name = "商品总重量", width = 20 });
            items.Add(new CellValueItem() { name = "是否开发票", width = 20 });
            items.Add(new CellValueItem() { name = "税号", width = 20 });
            items.Add(new CellValueItem() { name = "发票抬头", width = 20 });
            items.Add(new CellValueItem() { name = "使用积分", width = 20 });
            items.Add(new CellValueItem() { name = "积分抵扣金额", width = 20 });
            items.Add(new CellValueItem() { name = "订单优惠金额", width = 20 });
            items.Add(new CellValueItem() { name = "商品优惠金额", width = 20 });
            items.Add(new CellValueItem() { name = "优惠券优惠额度", width = 20 });
            items.Add(new CellValueItem() { name = "优惠券信息", width = 20 });
            items.Add(new CellValueItem() { name = "优惠信息", width = 20 });
            items.Add(new CellValueItem() { name = "买家备注", width = 20 });
            items.Add(new CellValueItem() { name = "下单IP", width = 20 });
            items.Add(new CellValueItem() { name = "卖家备注", width = 20 });
            items.Add(new CellValueItem() { name = "订单来源", width = 20 });
            items.Add(new CellValueItem() { name = "是否评论", width = 20 });
            items.Add(new CellValueItem() { name = "删除标志", width = 20 });
            items.Add(new CellValueItem() { name = "订单时间", width = 20 });
            items.Add(new CellValueItem() { name = "更新时间", width = 20 });

            var headerStyle = ExcelHelper.GetHeaderStyle(book);

            for (int i = 0; i < items.Count; i++)
            {
                var cell = row1.CreateCell(i);
                cell.SetCellValue(items[i].name);
                cell.CellStyle = headerStyle;
                sheet1.SetColumnWidth(i, items[i].width * 256);
            }

            row1.Height = 30 * 20;

            var commonCellStyle = ExcelHelper.GetCommonStyle(book);


            var detailsStartNumber = 0;
            var listStartNumber = 0;
            foreach (var order in list)
            {
                listStartNumber++;
                //当前开始行
                var nowNumber = detailsStartNumber;
                //将数据逐步写入sheet1各个行
                foreach (var t in order.items)
                {
                    var rowTemp = sheet1.CreateRow(detailsStartNumber + 1);

                    rowTemp.CreateCell(0).SetCellValue(listStartNumber);
                    rowTemp.CreateCell(1).SetCellValue(order.orderId);
                    rowTemp.CreateCell(2).SetCellValue(order.goodsAmount.ToString());
                    rowTemp.CreateCell(3).SetCellValue(order.payedAmount.ToString());
                    rowTemp.CreateCell(4).SetCellValue(order.orderAmount.ToString());

                    var payModel = orderPayStatusEntities.Find(p => p.value == order.payStatus);
                    rowTemp.CreateCell(5).SetCellValue(payModel != null ? payModel.description : "");

                    var shipStatusModel = shipStatusEntities.Find(p => p.value == order.shipStatus);
                    rowTemp.CreateCell(6).SetCellValue(shipStatusModel != null ? shipStatusModel.description : "");

                    var statusModel = orderStatusEntities.Find(p => p.value == order.status);
                    rowTemp.CreateCell(7).SetCellValue(statusModel != null ? statusModel.description : "");

                    var orderTypeModel = orderTypeEntities.Find(p => p.value == order.orderType);
                    rowTemp.CreateCell(8).SetCellValue(orderTypeModel != null ? orderTypeModel.description : "");

                    var paymentCodeModel = paymentsTypesEntities.Find(p => p.title == order.paymentCode);
                    rowTemp.CreateCell(9).SetCellValue(paymentCodeModel != null ? paymentCodeModel.description : "");

                    rowTemp.CreateCell(10).SetCellValue(order.paymentTime.ToString());


                    rowTemp.CreateCell(11).SetCellValue(!string.IsNullOrEmpty(t.addon) ? t.name + "【" + t.goodsId + "】规格：" + t.addon : "【" + t.goodsId + "】" + t.name);
                    rowTemp.CreateCell(12).SetCellValue(t.nums);
                    rowTemp.CreateCell(13).SetCellValue(t.price + "元");
                    rowTemp.CreateCell(14).SetCellValue(t.promotionAmount + "元");
                    rowTemp.CreateCell(15).SetCellValue(t.amount + "元");


                    rowTemp.CreateCell(16).SetCellValue(order.shipName);
                    rowTemp.CreateCell(17).SetCellValue(order.shipMobile);
                    rowTemp.CreateCell(18).SetCellValue(order.shipAreaName);

                    rowTemp.CreateCell(19).SetCellValue(!string.IsNullOrEmpty(order.logisticsName) ? order.logisticsName : "自提配送");
                    rowTemp.CreateCell(20).SetCellValue(order.costFreight.ToString());
                    rowTemp.CreateCell(21).SetCellValue(order.userId.ToString());

                    var confirmStatusModel = orderConfirmStatusEntities.Find(p => p.value == order.confirmStatus);
                    rowTemp.CreateCell(22).SetCellValue(confirmStatusModel != null ? confirmStatusModel.description : "");

                    rowTemp.CreateCell(23).SetCellValue(order.confirmTime.ToString());

                    rowTemp.CreateCell(24).SetCellValue(order.weight.ToString());
                    rowTemp.CreateCell(25).SetCellValue(order.taxType.ToString());
                    rowTemp.CreateCell(26).SetCellValue(order.taxCode);
                    rowTemp.CreateCell(27).SetCellValue(order.taxTitle);
                    rowTemp.CreateCell(28).SetCellValue(order.point.ToString());
                    rowTemp.CreateCell(29).SetCellValue(order.pointMoney.ToString());
                    rowTemp.CreateCell(30).SetCellValue(order.orderDiscountAmount.ToString());
                    rowTemp.CreateCell(31).SetCellValue(order.goodsDiscountAmount.ToString());
                    rowTemp.CreateCell(32).SetCellValue(order.couponDiscountAmount.ToString());
                    rowTemp.CreateCell(33).SetCellValue(order.coupon);
                    rowTemp.CreateCell(34).SetCellValue(order.promotionList);
                    rowTemp.CreateCell(35).SetCellValue(order.memo);
                    rowTemp.CreateCell(36).SetCellValue(order.ip);
                    rowTemp.CreateCell(37).SetCellValue(order.mark);
                    rowTemp.CreateCell(38).SetCellValue(order.source.ToString());
                    rowTemp.CreateCell(39).SetCellValue(order.isComment.ToString());
                    rowTemp.CreateCell(40).SetCellValue(order.isdel.ToString());
                    rowTemp.CreateCell(41).SetCellValue(order.createTime.ToString());
                    rowTemp.CreateCell(42).SetCellValue(order.updateTime.ToString());


                    rowTemp.Cells.ForEach(p =>
                    {
                        p.CellStyle = commonCellStyle;
                    });
                    rowTemp.Height = 20 * 20;


                    detailsStartNumber++;
                }
                //合并单元格（第几行，到第几行，第几列，到第几列）
                var marId = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 };
                if (order.items.Count <= 1) continue;
                foreach (var id in marId)
                {
                    sheet1.AddMergedRegion(new CellRangeAddress(nowNumber + 1, detailsStartNumber, id, id));
                }
            }

            // 写入到excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-订单导出(查询结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        #region 设置是否开发票============================================================
        // POST: Api/CoreCmsOrder/DoSettaxType/10
        /// <summary>
        /// 设置是否开发票
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否开发票")]
        public async Task<AdminUiCallBack> DoSettaxType([FromBody] FMUpdateIntegerDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.taxType = entity.data;

            var bl = await _coreCmsOrderServices.UpdateAsync(oldModel);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 设置是否评论============================================================
        // POST: Api/CoreCmsOrder/DoSetisComment/10
        /// <summary>
        /// 设置是否评论
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("设置是否评论")]
        public async Task<AdminUiCallBack> DoSetisComment([FromBody] FMUpdateBoolDataByIntId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.isComment = (bool)entity.data;

            var bl = await _coreCmsOrderServices.UpdateAsync(oldModel);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 更新备注============================================================
        // POST: Api/CoreCmsOrder/DoSetisdel/10
        /// <summary>
        /// 更新备注
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("更新备注")]
        public async Task<AdminUiCallBack> DoUpdateMark([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var oldModel = await _coreCmsOrderServices.QueryByIdAsync(entity.id);
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            oldModel.mark = entity.data.ToString();
            var bl = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { mark = oldModel.mark }, p => p.orderId == oldModel.orderId);
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

            return jm;
        }
        #endregion

        #region 取消订单============================================================
        // POST: Api/CoreCmsOrder/CancelOrder/10
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("取消订单")]
        public async Task<AdminUiCallBack> CancelOrder([FromBody] FMArrayStringIds entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.id.Length == 0)
            {
                jm.msg = "请提交要取消的订单号";
                return jm;
            }


            var result = await _coreCmsOrderServices.CancelOrder(entity.id);
            jm.code = result.status ? 0 : 1;
            jm.msg = result.msg;

            return jm;
        }
        #endregion

        #region 取消订单并退款============================================================
        // POST: Api/CoreCmsOrder/CancelOrderAndRefund/10
        /// <summary>
        /// 取消订单并退款
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("取消订单并退款")]
        public async Task<AdminUiCallBack> CancelOrderAndRefund([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.id.Length == 0)
            {
                jm.msg = "请提交要取消的订单号";
                return jm;
            }

            if (string.IsNullOrEmpty(entity.id))
            {
                jm.msg = "请提交要取消的订单号";
                return jm;
            }

            var result = await _coreCmsOrderServices.CancelOrderAndRefund(entity.id);

            //退款成功，还要去注销分销或者代理订单的状态取消。
            if (result.status)
            {
                //作废分销订单
                await _distributionOrderServices.CancleOrderByOrderId(entity.id);
                //作废代理订单
                await _agentOrderServices.CancelOrderByOrderId(entity.id);

            }

            jm.code = result.status ? 0 : 1;
            jm.msg = result.msg;

            return jm;
        }
        #endregion


        #region 批量删除订单============================================================
        // POST: Api/CoreCmsOrder/DeleteOrder/10
        /// <summary>
        /// 批量删除订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("批量删除订单")]
        public async Task<AdminUiCallBack> DeleteOrder([FromBody] FMArrayStringIds entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.id.Length == 0)
            {
                jm.msg = "请提交要批量删除的订单号";
                return jm;
            }

            var result = await _coreCmsOrderServices.UpdateAsync(p => new CoreCmsOrder() { isdel = true }, p => entity.id.Contains(p.orderId));
            jm.code = result ? 0 : 1;
            jm.msg = result ? "删除成功" : "删除失败";

            return jm;
        }
        #endregion

        #region 重新同步发货============================================================
        // POST: Api/CoreCmsOrder/DeleteOrder/10
        /// <summary>
        /// 重新同步发货
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("重新同步发货")]
        public async Task<AdminUiCallBack> RefreshDelivery([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            if (string.IsNullOrEmpty(entity.id))
            {
                jm.msg = "请提交要取消的订单号";
                return jm;
            }

            var delivery = await _billDeliveryServices.QueryByClauseAsync(p => p.deliveryId == entity.id);
            if (delivery == null)
            {
                jm.msg = "发货单获取失败";
                return jm;
            }

            jm.code = 0;
            jm.msg = "提交任务成功,请核实远端状态";

            return jm;
        }
        #endregion

        #region 预览快递进度============================================================
        // POST: Api/CoreCmsOrder/GetDetails/10
        /// <summary>
        /// 预览快递进度
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览快递进度")]
        public async Task<AdminUiCallBack> GetOrderLogistics([FromBody] FMStringId entity)
        {
            var jm = new AdminUiCallBack();

            var result = await _coreCmsOrderServices.GetOrderInfoByOrderId(entity.id);
            if (result == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = result.status ? 0 : 1;
            jm.data = result.data;

            return jm;
        }
        #endregion
        #region 提交订单============================================================
        // POST: Api/CoreCmsOrder/DoComplete/10
        /// <summary>
        /// 完成订单
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("提交订单")]
        //public async Task<AdminUiCallBack> SaveAddOrder([FromBody] CreateOrder entity )
         public async Task<AdminUiCallBack> SaveAddOrder([FromBody] CreateOrder entity )
        {
            var jm = new AdminUiCallBack();
            if (entity.id > 0)
            {
                var list = await _coreCmsNewCartServices.QueryListByClauseAsync(p=>p.number==entity.number);
                string goodsId = string.Empty;
                string goodsName = string.Empty;
                if (list.Count>0)
                {
                    foreach (var item in list)
                    {
                        goodsId = "" + item.productId + ",";
                        goodsName += goodsId;
                       // goodsId += goodsId;
                    }
                   // goodsId = goodsId.Split(',');
                }
                goodsId =goodsName.TrimEnd(',');
                var model = await _userServices.QueryByIdAsync(entity.id);
                jm = await _coreCmsOrderServices.CrmToAdd(entity.id, entity.number, goodsId, "",entity.address, model.userName,model.mobile,entity.orderAmount,entity.paymentCode,entity.mark,entity.orderTypeName,entity.sysid,entity.payedAmount);
            }
            //var count = await _coreCmsOrderServices.ToAdd(entity.id, entity.orderType, entity.goodsId, entity.receiptType,
            //   entity.ushipId, entity.storeId, entity.number, entity.ladingMobile, entity.memo,
            //   entity.point, entity.couponCode, entity.source, entity.scene, entity.taxType, entity.taxName,
            //   entity.taxCode, entity.objectId, entity.teamId, entity.requireOrder, entity.requiredFundType,
            //   entity.traceId);
            //jm = await _coreCmsOrderServices.ToAdd(_user.ID, entity.orderType, entity.cartIds, entity.receiptType,
            //entity.ushipId, entity.storeId, entity.ladingName, entity.ladingMobile, entity.memo,
            //entity.point, entity.couponCode, entity.source, entity.scene, entity.taxType, entity.taxName,
            //entity.taxCode, entity.objectId, entity.teamId, entity.requireOrder, entity.requiredFundType,
            //entity.traceId);
            //var result = await _coreCmsOrderServices.CompleteOrder(entity.id);
            //jm.code = result.status ? 0 : 1;
            //jm.msg = result.msg;
            //jm.data = result.data;
            //jm.otherData = result.otherData;

            return jm;

        }
        #endregion

        #region 跟进客户编号删除购物车============================================================
        // POST: Api/CoreCmsOrder/DoComplete/10
        /// <summary>
        /// 跟进客户编号删除购物车
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("根据客户编号删除购物车")]
        //public async Task<AdminUiCallBack> SaveAddOrder([FromBody] CreateOrder entity )
        public async Task<AdminUiCallBack> DeleteByNumber()
        {
            var jm = new AdminUiCallBack();
            var number = Request.Form["numberppp"].FirstOrDefault();
            if (!string.IsNullOrEmpty(number))
            {
                await _coreCmsNewCartServices.DeleteAsync(p => p.number == number);
                jm.code = 0;
            }

            return jm;

        }
        #endregion
        /// <summary>
        /// 跟进客户编号查询购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("跟进客户编号查询购物车")]
        public async Task<AdminUiCallBack> GetCartListByNumber()
        {
            var jm = new AdminUiCallBack();
            //客户编号 varchar
            var number = Request.Form["numberppp"].FirstOrDefault();
            //if (!string.IsNullOrEmpty(number))
            //{
            //   await _coreCmsNewCartServices.DeleteAsync(p=>p.number==number);
            //}
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsNewCart>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsNewCart, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "userId" => p => p.userId,
                "productId" => p => p.productId,
                "nums" => p => p.nums,
                "type" => p => p.type,
                "objectId" => p => p.objectId,
                "number" => p => p.number,
                "price" => p => p.price,
                "proName" => p => p.proName,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选
           

            if (!string.IsNullOrEmpty(number))
            {
                where = where.And(p => p.number.Contains(number));
            }
            //获取数据
            var list = await _coreCmsNewCartServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            jm.total= (decimal)list.Sum(p => p.price * p.nums);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "产品调用成功!";
            return jm;

        }


        /// <summary>
        /// 客户编号查询购物车是否存在
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("客户编号查询购物车是否存在")]
        public async Task<AdminUiCallBack> GetCartListBy([FromBody] FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            //设置排序方式

            //获取数据
            var list = await _coreCmsNewCartServices.QueryListByClauseAsync(p => p.number == entity.number);
           // jm.total = (decimal)list.Sum(p => p.price * p.nums);
            //返回数据
            jm.data = list;
            jm.code = 0;
            //jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }

        #region 修改产品============================================================
        // POST: Api/CoreCmsNewCart/Edit
        /// <summary>
        /// 修改产品
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("修改产品")]
        public async Task<AdminUiCallBack> DoEditNums([FromBody] CoreCmsOrderItemDTO entity)
        {
            var jm = new AdminUiCallBack();
            
            var model = await _orderItemServices.QueryByClauseAsync(p => p.id == entity.id);
            if (model.id > 0)
            {
                // CoreCmsNewCart newCart = new CoreCmsNewCart();
                model.id = entity.id;
                model.nums = entity.nums;
                model.amount = model.nums * model.price;
                bool bl = await _orderItemServices.UpdateAsync(model);
                if (bl)
                {
                    jm.code = 0;
                }
            }

            //var jm = await _CoreCmsNewCartServices.UpdateAsync(entity);
            return jm;
        }
        #endregion
        /// <summary>
        /// 跟进编号查询购买记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("跟进编号查询购买记录")]
        public async Task<AdminUiCallBack> GetCoreCmsOrderItem()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsOrderItem>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsOrderItem, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                _ => p => p.id
            };
            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //客户编号 varchar
            var number = Request.Form["number"].FirstOrDefault();
            if (!string.IsNullOrEmpty(number))
            {
                where = where.And(p => p.number==number);
            }
            var orderId= Request.Form["orderId"].FirstOrDefault();
            if (!string.IsNullOrEmpty(orderId))
            {
                where = where.And(p => p.orderId==orderId);
            }
            //获取数据
            var list = await _orderItemServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
          //  jm.total = (decimal)list.Sum(p => p.price * p.nums);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        /// <summary>
        /// 根据客户编号查询操作记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("根据客户编号查询操作记录")]
        public async Task<AdminUiCallBack> GetCoreCoreCmsOrderLogRecords()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreCmsOrderLog>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreCmsOrderLog, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                _ => p => p.id
            };
            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //客户编号 varchar
            var number = Request.Form["number"].FirstOrDefault();
            if (!string.IsNullOrEmpty(number))
            {
                where = where.And(p => p.number.Contains(number));
            }
            //获取数据
            var list = await _coreCmsOrderLogServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
           // jm.total = (decimal)list.Sum(p => p.price * p.nums);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #region 增加购物车============================================================
        // POST: Api/CoreCmsOrder/DoComplete/10
        /// <summary>
        /// 增加购物车
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("增加购物车")]
        //public async Task<AdminUiCallBack> SaveAddOrder([FromBody] CreateOrder entity )
        public async Task<AdminUiCallBack> SaveAddCart([FromBody] List<ProductDTO> list)
            {
             
            var jm = new AdminUiCallBack();
            var number = string.Empty;
            decimal total = 0;
            foreach (var item in list)
            {
                var modelInfo = await _coreCmsNewCartServices.QueryByClauseAsync(p=>p.productId==item.id&&p.number==item.number);

                if (modelInfo != null)
                {
                    var num= item.points;
                    modelInfo.nums+= num;
                    var flat=await _coreCmsNewCartServices.UpdateAsync(p => new CoreCmsNewCart() { nums=modelInfo.nums },p=>p.id==modelInfo.id);
                    if (flat==true)
                    {
                        jm.code = 0;
                        jm.msg = "数据添加成功";

                    }
                }
                else
                {
                    CoreCmsNewCart model = new CoreCmsNewCart();
                    model.number = item.number;
                    model.productId = item.id;
                    model.nums = item.points;
                    model.userId = item.userId;
                    number = item.number;
                    model.price = item.price;
                    model.proName = item.name;
                    jm = await _coreCmsNewCartServices.InsertAsync(model);
                    total += item.points * item.price;
                }
            }
            return jm;

        }
        #endregion
        #region 修改产品增加产品============================================================
        // POST: Api/CoreCmsOrder/DoComplete/10
        /// <summary>
        /// 修改产品增加产品
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("修改产品增加产品")]
        //public async Task<AdminUiCallBack> SaveAddOrder([FromBody] CreateOrder entity )
        public async Task<AdminUiCallBack> AddOrderItem([FromBody] List<ProductDTO> list)
        {

            var jm = new AdminUiCallBack();
            var number = string.Empty;
            decimal total = 0;
            foreach (var item in list)
            {
                var modelInfo =  await _orderItemServices.QueryByClauseAsync(p => p.orderId == item.orderId && p.productId == item.id);

                if (modelInfo != null)
                {
                    var num = item.points;
                    modelInfo.nums += num;
                    var price= item.price*modelInfo.nums;
                    var flat = await _orderItemServices.UpdateAsync(p => new CoreCmsOrderItem() { nums = modelInfo.nums,amount=price }, p => p.id == modelInfo.id);
                    if (flat == true)
                    {
                        jm.code = 0;
                        jm.msg = "更新产品成功";

                    }
                }
                else
                {
                    CoreCmsOrderItem order = new CoreCmsOrderItem();
                    var proModel=await _coreCmsProductsServices.QueryByClauseAsync(p => p.id == item.id);
                    order.orderId = item.orderId;
                    order.goodsId = proModel.goodsId;
                    order.productId = item.id;
                    order.number = item.number;
                    order.sn = proModel.sn;
                    order.bn = string.Empty;
                    order.name = item.name;
                    order.price = item.price;
                  
                    order.mktprice = 0;
                    order.costprice = 0;
                    order.nums = item.points;
                    order.imageUrl = proModel.images;

                    order.amount = item.points*item.price;
                    order.promotionAmount = 0;
                    order.promotionList = string.Empty;
                    order.weight = 0;
                    order.sendNums = 0;
                    order.addon = string.Empty;
                    order.createTime= DateTime.Now;
                    order.orderAmount = 0;
                    order.updateTime= DateTime.Now;
                    int code = await _orderItemServices.InsertAsync(order);
                    if (code>0)
                    {
                        jm.msg = "更新产品成功";
                        jm.code = 0;
                    }
                }
            }
            return jm;

        }
        #endregion
        #region 快递轨迹============================================================
        // POST: Api/CoreCmsOrder/DoComplete/10
        /// <summary>
        /// 增加购物车
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("快递轨迹")]
        //public async Task<AdminUiCallBack> SaveAddOrder([FromBody] CreateOrder entity )
        public async Task<AdminUiCallBack> Expressdelivery(string code,string expressNumber)
        {

            var jm = new AdminUiCallBack();
            //快递100分配给贵司的的公司编号, 请在企业管理后台查看
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var customer = "F6825F783831003EAF8920021BC90C1F";
            //签名， 用于验证身份， 按param + key + customer 的顺序进行MD5加密（注意加密后字符串一定要转大写）， 不需要加上“+”号， 如{“com”: “yuantong”, “num”: “500306190180”, “from”: “广东省深圳市”, “to”: “北京市朝阳区”}xxxxxxxxxxxxyyyyyyyyyyy yyyyyyyyyyyyyyyyyyyyy
            var key = "reLmQOdC3386";

            if (string.IsNullOrEmpty(customer) || string.IsNullOrEmpty(key))
            {
                jm.msg = "快递查询接口公司编码及授权key获取失败";
            }

            var param = new KuaiDi100ApiPostParam();
            param.com =code.ToLowerInvariant();
            param.num = expressNumber;
            param.phone = "";
            param.from = "";
            param.to = "";
            param.resultv2 = 1;
            var jsonParamData = JsonConvert.SerializeObject(param);

            //签名加密
            var str = jsonParamData + key + customer;
            var signStr = CommonHelper.Md5For32(str).ToUpper();
            //实时查询请求地址
            var postUrl = "http://poll.kuaidi100.com/poll/query.do";

            var postData = new
            {
                customer,
                param = jsonParamData,
                sign = signStr
            };

            var result = await postUrl.PostUrlEncodedAsync(postData).ReceiveJson<KuaiDi100ApiPostResult>();
            if (result.status == "200")
            {
               // jm.status = true;
                jm.data = result;
            }
            else
            {
              //  jm.status = false;
                jm.msg = !string.IsNullOrEmpty(result.message) ? result.message : "暂无消息";
            }

            return jm;

        }
        #endregion
    }
}
